﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.Security;

namespace SweetSurvey.Models.Repositories
{
    public class SurveyRepository: RepositoryBase, ISurveyRepository
    {
        #region IRepository<Survey,string> Members

        public Survey Get(string id, bool detaching = true)
        {
            var context = new SweetSurveyModelContainer();
            var result = context.Surveys.Where(s => s.Id == id).Single();
            if (detaching) { context.Detach(result); }
            return result;
        }

        public string Create(Survey entity)
        {
            if (string.IsNullOrEmpty(entity.Id)) { entity.Id = RepositoryBase.GenerateRandomId(); }
            if (entity.Title == null) { entity.Title = string.Empty; }
            var context = new SweetSurveyModelContainer();
            context.Surveys.AddObject(entity);
            context.SaveChanges();
            return entity.Id;
        }

        public void Update(Survey entity)
        {
            RepositoryBase.Update(entity);
        }

        public void Delete(string id)
        {
            RepositoryBase.Delete(Get(id));
        }

        #endregion

        #region ISurveyRepository Members

        public IQueryable<Survey> GetSurveysByEditorId(string id)
        {
            var context = new SweetSurveyModelContainer();
            return context.Surveys.Where(s => s.EditorId == id).OrderByDescending(s => s.DateCreated);
        }

        public IQueryable<Survey> GetAllSurveys()
        {
            var context = new SweetSurveyModelContainer();
            return context.Surveys.OrderByDescending(s => s.DateCreated);
        }

        public void AssertOwner(string id, string userName)
        {
            var context = new SweetSurveyModelContainer();
            var survey = context.Surveys.Where(s => s.Id == id).Single();
            if (!survey.EditorId.Equals(userName, StringComparison.OrdinalIgnoreCase))
            {
                throw new SecurityException("Owner assertion failed");
            }
        }

        #endregion
    }
}